package com.sl.au.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.sl.au.entity.M2R;
import com.sl.au.entity.Module;
import com.sl.au.entity.Role;
import com.sl.au.repository.AccountRepository;
import com.sl.au.repository.M2RRepository;
import com.sl.au.repository.ModuleRepository;
import com.sl.au.repository.RoleRepository;
import com.sl.au.service.M2RService;
@Service("M2RService")
@Transactional
public class M2RServiceImpl extends BaseServiceImpl implements M2RService {

	@Autowired
	ModuleRepository moduleRepository;
	@Autowired
	RoleRepository roleRepository;
	@Autowired
	AccountRepository accountRepository;
	@Autowired
	M2RRepository m2RRepository;


	@Override
	public void M2R(List<String> moduleIds, String roleId) {
	
	
		Role role=roleRepository.findOne(roleId);
		List<Module> list=new ArrayList<Module>();
		Module module=null;
		if(null==role) return;
		if(moduleIds==null ) {
			//清空权限
			role.setModules(null);		
		}
		else{
			for(String id:moduleIds){
				module=new Module();
				module.setId(id);
				list.add(module);
			}
			role.setModules(list);
		}
		roleRepository.save(role);
	}

	public M2RRepository getRepository(){
		return this.m2RRepository;
	}

	@Override
	public List<M2R> getModules(int start, int length, Role role, String orderName, String dir){
		Page<M2R> pages = null;
		Pageable pageable=new PageRequest(start/length,length, Sort.Direction.ASC,"module.menuIndex");
		pages = m2RRepository.findByRole(role, pageable);
		return pages.getContent();
	}
    @Override
	public List<Module> getModulesNot(int start, int length, Role role,String orderName ,String dir){
		Page<Module> pages = null;
		Pageable pageable=new PageRequest(start/length,length, Sort.Direction.DESC,"id");
		pages = m2RRepository.findModuleNot(role,pageable);
		return pages.getContent();
	}
}
